'use client';
import PageTitle from '@/components/admin/common/PageTitle';
import Loading from '@/components/common/Loading';
import message from '@/components/common/message';
import request from '@/utils/request';
import { useRouter } from 'next/navigation';
import React, { useEffect, useState, use, useCallback } from 'react'
import { SimpleEditor } from "@/components/tiptap-templates/simple/simple-editor"
import SuperInput from '@/components/admin/common/SuperInput';
import SuperCheckbox from '@/components/admin/common/SuperCheckbox';
import ImageUpload from '@/components/admin/common/ImageUpload';
import SuperSelect from '@/components/admin/common/SuperSelect';

export default function Pages({ params }) {
  const { id } = use(params)
  const [loaded, setLoaded] = useState(false);
  const [pageValue, setPageValue] = useState({});
  const router = useRouter();

  const fetchPage = useCallback(async () => {
    if (loaded) return;
    const res = await request(`/api/admin/pages/${id}`, { method: 'GET' });
    if (res.code === 0) {
      setPageValue(res.data);
      setLoaded(true);
    } else {
      message.error(res.codeMap[res.code]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  useEffect(() => {
    fetchPage();
    return () => setLoaded(false);
  }, [fetchPage]);

  const changeHandle = (key, value) => {
    setPageValue(prev => { return { ...prev, [key]: value } });
  }

  const returnToLastPage = () => {
    router.back();
  }

  const savePageInfo = async () => {
    if (!pageValue.title) {
      message.error('页面标题不能为空');
      return;
    }
    const res = await request(`/api/admin/pages`, { method: 'PUT', body: JSON.stringify(pageValue) });
    if (res.code === 0) {
      message.success('保存成功');
      setLoaded(false);
      fetchPage();
    } else {
      message.error(res.codeMap[res.code]);
    }
  };

  const content = (
    <div className='editor'>
      <PageTitle title={`${pageValue?.title} - 编辑`} extraButtonText={'返回上一页'} onExtraButtonClick={returnToLastPage} buttonText={'保存'} onButtonClick={savePageInfo} />
      <div className='mx-auto rounded-xs shadow-xs my-1 flex gap-4'>
        <div className='content flex-3 flex flex-col gap-4'>
          <div className='bg-white p-4 rounded-sm'>
            <SuperInput className={`w-full!`} value={pageValue?.title} state={true} handleChange={(value) => changeHandle('title', value)} placeholder='请输入页面标题' label='标题' />
            <SuperInput className={`w-full!`} value={pageValue?.description} state={true} handleChange={(value) => changeHandle('description', value)} placeholder='请输入页面描述' label='描述' />
            <div className='max-h-[500px] overflow-y-auto'>
              <div className='form-label text-sm text-gray-600 mb-1'>内容:</div>
              <SimpleEditor onChange={(value) => changeHandle('content', value)} value={pageValue?.content} className={'border border-gray-300 rounded p-2'} />
            </div>
          </div>
          <div className='bg-white p-4 rounded-sm'>
            <SuperInput className={`w-full!`} value={pageValue?.slug} state={true} handleChange={(value) => changeHandle('slug', value)} placeholder='请输入页面别名' label='别名（用于搜索引擎优化，不填写会自动生成）' />
            <SuperInput className={`w-full!`} value={pageValue?.meta_title} state={true} handleChange={(value) => changeHandle('meta_title', value)} placeholder='请输入Meta标题' label='Meta标题（用于搜索引擎优化）' />
            <SuperInput className={`w-full!`} value={pageValue?.meta_description} state={true} handleChange={(value) => changeHandle('meta_description', value)} placeholder='请输入Meta描述' label='Meta描述（用于搜索引擎优化）' />
            <SuperInput className={`w-full!`} value={pageValue?.slug && `${window && window.location.origin}/pages/${pageValue.slug}`} state={false} handleChange={(value) => changeHandle('url', value)} label='访问链接' />
          </div>
        </div>
        <div className='silder flex-1 bg-white p-4 rounded-sm h-fit sticky top-[64px]'>
          <SuperCheckbox className={`w-full!`} value={pageValue?.status} state={true} checked={pageValue?.status === 0 ? true : false} onChange={(value) => changeHandle('status', value ? 0 : 1)} label='状态' />
          <SuperSelect className={`w-full!`} value={pageValue?.template} state={true} onChange={(value) => changeHandle('template', value)} label={'模板'} placeholder='选择模板' options={pageValue?.templates || []} />
          <ImageUpload className={`w-full!`} value={pageValue?.cover} state={true} handleChange={(value) => changeHandle('cover', value)} placeholder='上传封面图片' label='封面图片' />
          <SuperInput className={`w-full!`} value={pageValue?.created_at && new Date(pageValue?.created_at).toLocaleString()} state={false} handleChange={(value) => changeHandle('created_at', value)} placeholder='创建时间' label='创建时间' />
          <SuperInput className={`w-full!`} value={pageValue?.updated_at && new Date(pageValue?.created_at).toLocaleString()} state={false} handleChange={(value) => changeHandle('updated_at', value)} placeholder='创建时间' label='创建时间' />
        </div>
      </div>
    </div>
  )

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  )
}
